//
//  BrandsViewController.m
//  CheXunWang
//
//  Created by zhu lin on 12/14/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "BrandsViewController.h"
#import "HttpServices.h"
#import "StorageService.h"
#import "HomeViewController.h"
#import "SeriesViewController.h"
#import "CheXunWangAppDelegate.h"
#import <QuartzCore/QuartzCore.h>

/*
 {"brandId":2,
 "logo":"http://img01.chexun.com/images/logo/default/201178162029821792014.gif",
 "letter":"A",
 "brandName":"(A)奥迪"}
 */

#define kDefaultSectionNum		1
#define kDefaultCellNum			1
#define kCustomSectionHeight	20.0
#define kCustomCellHeight		90.0
#define kCustomBlankCellHeight	367.0

#define kSectionKey				@"letter"
#define kImageKey				@"logo"
#define kBrandNameKey			@"brandName"
#define kBrandIdKey				@"brandId"

#define kImageTag				1001
#define kBrandNameTag			1002

@interface BrandsViewController()
@property (nonatomic, retain) ASIHTTPRequest *brandslistRequest;
@property (nonatomic, retain) NSMutableDictionary *imageDownloadsInProgress;

- (void) showHomeView:(id)sender;
- (UIImage *)loadImageOfIndexPath:(NSIndexPath *)indexPath;
- (void)loadImagesForOnscreenRows;
@end

@implementation BrandsViewController
@synthesize hud;
@synthesize groupedBrandArray;
@synthesize brandslistRequest;
@synthesize imageDownloadsInProgress;

- (ATMHud *)hud
{
	if (hud == nil) {
		hud = [[ATMHud alloc] init];
		[self.view addSubview:hud.view];
	}
	return hud;
}

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"品牌";
    self.navigationItem.hidesBackButton = YES;
	
	UIButton *homeButton = [UIButton buttonWithType:UIButtonTypeCustom];
	homeButton.frame = CGRectMake(0.0f, 8.0f, 87.0f, 27.0f);
	[homeButton addTarget:self action:@selector(showHomeView:) forControlEvents:UIControlEventTouchUpInside];
	[homeButton setImage:[UIImage imageNamed:@"ios_common_titlebar_logo.png"] forState:UIControlStateNormal];
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];
	self.tableView.tableFooterView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 0)] autorelease];
	
	self.groupedBrandArray = [NSMutableArray array];
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
}

/*
-(void)setNavigationTitle:(NSString *)title
{
	if(self.navigationItem.titleView == nil)
	{
		UIView *titleView = [[UIView alloc] init];
		
		UIImageView *bgTitleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"choosepaper.png"]];
		bgTitleImage.tag = 1;
		[titleView addSubview:bgTitleImage];
		[bgTitleImage release];
		
		UILabel *titleLabel = [[UILabel alloc] init];
		titleLabel.tag = 2;
		titleLabel.textColor = [UIColor whiteColor];
		titleLabel.backgroundColor = [UIColor clearColor];
		titleLabel.font = [UIFont boldSystemFontOfSize:kNavicationTitleFontSize];
		[titleView addSubview:titleLabel];
		[titleLabel release];
		
		UIImageView *indicatorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paperbuttondown.png"]];
		indicatorImage.tag = 3;
		[titleView addSubview:indicatorImage];
		[indicatorImage release];
		
		UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[titleButton addTarget:self action:@selector(navigationButtonPressed) forControlEvents:UIControlEventTouchUpInside];
		titleButton.tag = 4;
		[titleView addSubview:titleButton];
		
		[self.navigationItem setTitleView:titleView];
		[titleView release];
	}
	
	CGSize titleSize = [title sizeWithFont:[UIFont boldSystemFontOfSize:kNavicationTitleFontSize]];
	
	UIImageView *bgTitleImage = (UIImageView *)[self.navigationItem.titleView viewWithTag:1];
	bgTitleImage.frame = CGRectMake(0, 0.0, 160.0, 44.0);
	bgTitleImage.hidden = YES;
	
	UILabel *titleLabel = (UILabel *)[self.navigationItem.titleView viewWithTag:2];
	titleLabel.frame = CGRectMake((160.0 - titleSize.width - 5.0 - 13.0)/2, 7.0, titleSize.width, 30.0);
	titleLabel.text = title;
	
	UIImageView *indicatorImage = (UIImageView *)[self.navigationItem.titleView viewWithTag:3];
	indicatorImage.frame = CGRectMake(titleLabel.frame.origin.x + titleSize.width + 5.0, 13.0, 13.0, 17.0);
	
	UIButton *titleButton = (UIButton *)[self.navigationItem.titleView viewWithTag:4];
	titleButton.frame = bgTitleImage.frame;
	
	//self.navigationItem.titleView.frame = CGRectMake((320-(titleSize.width + 15 +13))/2, 0.0, titleSize.width + 15.0 + 13.0, 44.0);
	self.navigationItem.titleView.frame = CGRectMake(80, 0.0, 160, 44.0);
	self.navigationItem.title = title;
}
*/

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	int count = [self.groupedBrandArray count];
	
    if (count == 0) {
		return kDefaultSectionNum;
	}
	
	return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([self.groupedBrandArray count] == 0) {
		return kDefaultCellNum;
	}
	
    NSArray *subArray = [self.groupedBrandArray objectAtIndex:section];
	if (subArray && [subArray count] > 0) {
		return [subArray count];
	}
	
	return kDefaultCellNum;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([self.groupedBrandArray count] == 0) {
		return kCustomBlankCellHeight;
	}
	
	return kCustomCellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	if ([self.groupedBrandArray count] == 0) {
		return nil;
	}
	
	UIView *customSectionView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, kCustomSectionHeight)];
	UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ios_common_list_title_bg.png"]];
	backImageView.frame = CGRectMake(0.0, 0.0, 320.0, kCustomSectionHeight);
	[customSectionView addSubview:backImageView];
	[backImageView release];
	UILabel *companyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 300.0f, kCustomSectionHeight)];
	companyLabel.backgroundColor = [UIColor clearColor];
	companyLabel.textColor = [UIColor colorWithRed: 0.2 green: 0.2 blue: 0.2 alpha: 1.0];
	companyLabel.font = [UIFont systemFontOfSize:12.0f];
	companyLabel.text = (NSString *)[[[self.groupedBrandArray objectAtIndex:section] objectAtIndex:0] valueForKey:kSectionKey];
	[customSectionView addSubview:companyLabel];
	[companyLabel release];
	return customSectionView;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *blankCellIdentifier = @"blankCell";
	static NSString *brandCellIdentifier = @"brandCell";
    
	if ([self.groupedBrandArray count] == 0) {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:blankCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
										   reuseIdentifier:blankCellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		return cell;
	}
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:brandCellIdentifier];
    if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:brandCellIdentifier];
		
		UIImage *backImage = [UIImage imageNamed:@"ios_common_list_item_normal.png"];
		UIImageView *backImageView = [[UIImageView alloc] initWithImage:[backImage stretchableImageWithLeftCapWidth:5.0 topCapHeight:10.0]];
		[cell setBackgroundView:backImageView];
		[backImageView release];
		
		UIImage *selectedBackImage = [UIImage imageNamed:@"ios_common_list_item_pressed.png"];
		UIImageView *selectedBackImageView = [[UIImageView alloc] initWithImage:[selectedBackImage stretchableImageWithLeftCapWidth:5.0 topCapHeight:10.0]];
		[cell setSelectedBackgroundView:selectedBackImageView];
		[selectedBackImageView release];
		
		// add image
		UIImageView *brandImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 80.0f, 80.0f)];
		[[brandImageView layer] setCornerRadius:5.0f];
		brandImageView.tag = kImageTag;
		[cell.contentView addSubview:brandImageView];
		[brandImageView release];
		
		// add name
		UILabel *brandNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 30.0, 200.0f, 30.0f)];
		brandNameLabel.backgroundColor = [UIColor clearColor];
		brandNameLabel.font = [UIFont systemFontOfSize:18.0];
		brandNameLabel.textColor = [UIColor colorWithRed:29.0/255.0 green:29.0/255.0 blue:29.0/255.0 alpha:1.0];
		brandNameLabel.tag = kBrandNameTag;
		[cell.contentView addSubview:brandNameLabel];
		[brandNameLabel release];
	}
    
    // Configure the cell...
	NSDictionary *dic = (NSDictionary *)[[self.groupedBrandArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	UILabel *brandNameLabel = (UILabel *)[cell.contentView viewWithTag:kBrandNameTag];
	brandNameLabel.text = (NSString *)[dic objectForKey:kBrandNameKey];
	
	// handle image
	UIImageView *brandImage = (UIImageView *)[cell.contentView viewWithTag:kImageTag];
	brandImage.image = [self loadImageOfIndexPath:indexPath];
	
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.groupedBrandArray count] == 0) {
		return;
	}
	
	NSDictionary *dic = (NSDictionary *)[[self.groupedBrandArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	
    SeriesViewController *seriesVC = [[SeriesViewController alloc] initWithNibName:@"SeriesViewController" bundle:nil];
	seriesVC.title = (NSString *)[dic objectForKey:kBrandNameKey];
	seriesVC.backType = ZLBackButtonTypeBrand;
	
	//
	[self.navigationController pushViewController:seriesVC animated:YES];
	[seriesVC getSeriesByBrandId:[[dic objectForKey:kBrandIdKey] stringValue]];
	[seriesVC release];
	
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark image download methods
- (UIImage *)loadImageOfIndexPath:(NSIndexPath *)indexPath
{
	NSDictionary *dic = (NSDictionary *)[[self.groupedBrandArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	NSString *imageURL = (NSString *)[dic valueForKey:kImageKey];
	NSString *imageName = (NSString *)[[imageURL componentsSeparatedByString:@"/"] lastObject];
	NSString *imagePath = [StorageService getPathByStorageType:ZLStorageTypeBrandImage withFileName:imageName];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
		return [UIImage imageWithContentsOfFile:imagePath];
	} else {
		ASIHTTPRequest *request = [self.imageDownloadsInProgress objectForKey:indexPath];
		if (request == nil && self.tableView.dragging == NO && self.tableView.decelerating == NO) {
			request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageURL]];
			[request setDelegate:self];
			[request setDownloadDestinationPath:imagePath];
			[request startAsynchronous];
			[self.imageDownloadsInProgress setObject:request forKey:indexPath];
		}
	}
	
	return [UIImage imageNamed:@"ios_common_list_item_avatar.png"];
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
	if ([self.groupedBrandArray count] > 0)
	{
		NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
		for (NSIndexPath *indexPath in visiblePaths)
		{
			[self loadImageOfIndexPath:indexPath];
		}
	}
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate 
{
	if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

#pragma mark -
#pragma mark Memory management
- (void)viewDidDisappear:(BOOL)animated
{
	for(ASIHTTPRequest *request in [self.imageDownloadsInProgress allValues])
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.brandslistRequest clearDelegatesAndCancel];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
	for(ASIHTTPRequest *request in self.imageDownloadsInProgress)
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.brandslistRequest clearDelegatesAndCancel];
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	self.hud = nil;
	self.groupedBrandArray = nil;
	self.brandslistRequest = nil;
	self.imageDownloadsInProgress = nil;
}


- (void)dealloc {
	[brandslistRequest release];
	[imageDownloadsInProgress release];
	[groupedBrandArray release];
	[hud release];
    [super dealloc];
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {	
		// brandslist request
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		
		NSArray *ungroupedArray = (NSArray *)[result JSONValue];
		if (!ungroupedArray || [ungroupedArray count] == 0) {
			self.groupedBrandArray = [NSMutableArray array];
		} else {
			self.groupedBrandArray = [HttpServices groupArray:ungroupedArray byKey:kSectionKey];
		}
		
		[self.hud hide];
		[self.tableView reloadData];
	} else {
		// loadimage request
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
		UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kImageTag];
		imageView.image = [self loadImageOfIndexPath:indexPath];
		[[imageView layer] setCornerRadius:5.0f];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
		[self.hud setCaption:@"访问出错！"];
		[self.hud setImage:[UIImage imageNamed:@"11-x"]];
		[self.hud setActivity:NO];
		[self.hud update];
		[self.hud hideAfter:1.0f];
	} else {
		// stop loadimage
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}
}

#pragma mark -
#pragma mark actions
- (void)getAllBrands
{
	self.brandslistRequest = [HttpServices getBrandsByBrandID:nil andBrandName:nil delegate:self];
	
	// show hud
	[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
	[self.hud setCaption:@"正在载入"];
	[self.hud setActivity:YES];
	[self.hud show];
}

- (void) showHomeView:(id)sender
{
	if (![NSThread isMainThread]) {
		[self performSelectorOnMainThread:@selector(showHomeView:) withObject:nil waitUntilDone:NO];
		return;
	}
	
	HomeViewController *homeVC = [HomeViewController sharedViewController];
	[self.navigationController presentModalViewController:homeVC animated:YES];
	//UINavigationController *nav = [[CheXunWangAppDelegate shareAppDelegate].tabbarController.viewControllers objectAtIndex:0];
	//[nav popToRootViewControllerAnimated:NO];
}
@end

